<template>
  <div class="info_main mt-5 ml-5">
    <!--    搜素框  -->
    <div class="row" >
      <div class="col-md-2">
<!--        <el-button @click="toggleSelection()">取消选择</el-button>-->
        <el-select v-model="fiter_check" placeholder="选择审核情况..." @change="changecheck">
          <el-option label="审核通过" value="1"></el-option>
          <el-option label="审核不通过" value="2"></el-option>
          <el-option label="未审核" value="0"></el-option>
        </el-select>
      </div>
      <div class="col-md-8">
        <el-input  type="text"
                   v-model="findName"
                   style="width: 500px;"
                   placeholder="请输入帖子标题..."
                   clearable
                   @keyup.enter.native="searchByTitle">
        </el-input>
        <el-button type="primary" icon="el-icon-search" @click="searchByTitle()" class="ml-3" plain>搜索</el-button>
        <el-button type="info" icon="el-icon-delete" @click="clearFindInput()" class="ml-3">重置</el-button>
      </div>
      <!--      添加按钮-->
      <!--      <div class="col-md-4" align="right">-->
      <!--        <el-button type="primary" @click="addOpen()" plain><i class="el-icon-plus" ></i>添加</el-button>-->
      <!--      </div>-->
    </div>
    <!--      批量审核按钮-->
    <div class="mt-3">
      <el-button @click="toggleSelection()">取消选择</el-button>
      <el-button type="danger" @click="handleMultipleDelete">批量删除</el-button>
      <el-button type="warning" @click="handleMultipleCheck">批量审核</el-button>
    </div>
    <div class="show_data mt-4">
      <el-table
          ref="multipleTable"
          v-horizontal-scroll="'always'"
          show-overflow-tooltip
          :data="showData"
          style="width: 100%"
          :cell-style="{color: '#666', fontFamily: 'Arial',fontSize:'17px'}"
          :header-cell-style="{background:'whitesmoke', fontFamily:'Helvetica',fontSize:'20px'}"
          height="700"
          @selection-change="handleSelectionChange"
          @filter-change="filterChange"
          :filter-method="filterHandler"
          tooltip-effect="dark"
          :default-sort = "{prop: 'date', order: 'descending'}">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            prop="post_title"
            label="标题"
            width="200">
        </el-table-column>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="内容：">
                <span>{{ props.row.post_content }}</span>
              </el-form-item>
              <el-form-item label="图片：" v-show="props.row.post_img!='default_post_img.jpg'">
                <img :src="'/api/storage/post_img/'+props.row.user_id+'/'+props.row.post_img"
                     style="width:30%;height:30%;object-fit:contain;border-radius: 2px"  alt="...">
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column
            prop="user_name"
            label="发布者"
            width="100">
        </el-table-column>
        <el-table-column
            prop="idle_item_check"
            label="审核情况"
            width="120"
            column-key="post_check">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.post_check==1" disable-transitions type="success">
              <span class="typeClass">审核通过</span>
            </el-tag>
            <el-tag v-else-if="scope.row.post_check==2" disable-transitions type="danger">
              <span class="typeClass">审核不通过</span>
            </el-tag>
            <el-tag v-else-if="scope.row.post_check==0" disable-transitions type="primary">
              <span class="typeClass">未审核</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            fixed
            prop="post_time"
            label="编辑时间"
            width="220">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ scope.row.post_time }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="cnt"
            label="评论数"
            width="90">
          <template slot-scope="scope">
            <span >{{ scope.row.cnt }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="post_category"
            label="类别"
            width="150">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.post_category==1" disable-transitions type="primary">
              <span class="typeClass">求助问答</span>
            </el-tag>
            <el-tag v-else-if="scope.row.post_category==2" disable-transitions type="success">
              <span class="typeClass">学长学姐说</span>
            </el-tag>
            <el-tag v-else-if="scope.row.post_category==3" disable-transitions type="danger">
              <span class="typeClass">日常生活</span>
            </el-tag>
            <el-tag v-else-if="scope.row.post_category==4" disable-transitions type="warning">
              <span class="typeClass">其他</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="260">
          <template slot-scope="scope">
            <el-button
                type="warning"
                size="mini"
                @click="check(scope.$index, scope.row)">
              <span class="btnfontClass">审核</span>
            </el-button>
            <el-button
                type="success"
                size="mini"
                @click="edit(scope.$index, scope.row)">
              <span class="btnfontClass" >编辑</span>
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">
              <span class="btnfontClass" >删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--    分页-->
      <div class="pagin mt-5 mb-5">
        <el-pagination
            @current-change="handleCurrentChange"
            :current-page="postContainerPage"
            :page-size="postContainerSize"
            layout="total, prev, pager, next"
            :total=total>
        </el-pagination>
      </div>

      <!--编辑弹窗-->
      <el-dialog
          title="编辑帖子"
          :visible.sync="editdialogVisible"
          width="60%">

        <!--        编辑表单-->
        <el-form ref="Editform" :model="Editform" label-width="100px" :rules="rules">


          <el-form-item label="帖子标题" :label-width="formLabelWidth" prop="post_title">
            <el-input v-model="Editform.post_title"
                      type="text"
                      maxlength="50"
                      autocomplete="off"
                      show-word-limit
                      placeholder="请输入帖子标题，3-50个字符...">
            </el-input>
          </el-form-item>

          <el-row>
            <el-col :span="12">
              <el-form-item label="帖子类别" :label-width="formLabelWidth" prop="post_category">
                <el-select  placeholder="选择帖子类别..." v-model="Editform.post_category">
                  <el-option v-for="(category) in category" :label="category.label" :value="category.id" :key="category.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="帖子标签" :label-width="formLabelWidth" prop="post_label">
                <el-input v-model="Editform.post_label"
                          type="text"
                          maxlength="20"
                          autocomplete="off"
                          show-word-limit
                          placeholder="请输入帖子标签，3-20个字符...">
                </el-input>
              </el-form-item>
            </el-col>

          </el-row>

          <el-form-item label="帖子内容" :label-width="formLabelWidth" prop="post_content">
            <el-input
                show-word-limit
                type="textarea"
                maxlength="2000"
                :rows="20"
                placeholder="请输入内容，1-2000个字符"
                v-model="Editform.post_content">
            </el-input>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="editSave('Editform')">修 改</el-button>
          <el-button @click="openCancelEdit">取 消</el-button>
        </span>

      </el-dialog>

      <!--添加弹窗-->
      <el-dialog
          title="添加考研资讯"
          :visible.sync="addialogVisible"
          width="70%"
          @close="handleClose">

        <!--        添加表单-->
        <el-form ref="Addform" :model="Addform" label-width="100px" :rules="rules" :before-close="closeDiv">


          <el-row>
            <el-col :span="12">
              <el-form-item label="标题" :label-width="formLabelWidth" prop="pee_title">
                <el-input
                    show-word-limit
                    v-model="Addform.pee_title"
                    maxlength="100"
                    :rows="2"
                    type="text">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="类别" :label-width="formLabelWidth" prop="pee_category">
                <el-select v-model="Addform.pee_category" placeholder="选择考研资讯类别...">
                  <el-option label="考研信息" value="1" name="考研信息"></el-option>
                  <el-option label="招生信息" value="2" name="招生信息"></el-option>
                  <el-option label="考研日报" value="3" name="考研日报"></el-option>
                  <el-option label="特别推荐" value="4" name="特别推荐"></el-option>
                  <el-option label="其他" value="0" name="其他"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="标签" :label-width="formLabelWidth" prop="pee_label">
            <el-input
                show-word-limit
                v-model="Addform.pee_label"
                maxlength="100"
                type="text">
            </el-input>
          </el-form-item>


          <el-form-item label="来源" :label-width="formLabelWidth" prop="pee_source">
            <el-input
                show-word-limit
                v-model="Addform.pee_source"
                maxlength="100"
                type="text">
            </el-input>
          </el-form-item>


          <el-form-item label="内容" :label-width="formLabelWidth" prop="pee_content">
            <el-input
                show-word-limit
                type="textarea"
                maxlength="5000"
                :rows="20"
                v-model="Addform.pee_content"></el-input>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitAdd('Addform')">发 布</el-button>
          <el-button @click="cancel">取 消</el-button>
          <el-button @click="clearInput('Addform')">重 置</el-button>
        </span>
      </el-dialog>

      <!--审核情况-->
      <el-dialog title="审 核 情 况" :visible.sync="checkdialogFormVisible" width="30%">
        <el-form :model="checkform">
          <el-form-item label="审核情况：" :label-width="formLabelWidth">
            <el-select v-model="checkform.check" placeholder="审核情况...">
              <el-option label="通过审核" value="1"></el-option>
              <el-option label="不通过审核" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="checkdialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitCheck">确 定</el-button>
        </div>
      </el-dialog>


      <!--      批量审核-->
      <el-dialog title="审 核 情 况" :visible.sync="mulipleCheckdialogFormVisible" width="30%">
        <el-form :model="mulipleIdle">
          <el-form-item label="审核情况：" :label-width="formLabelWidth">
            <el-select v-model="mulipleIdle.multipleCheck" placeholder="审核情况...">
              <el-option label="通过审核" value="1"></el-option>
              <el-option label="不通过审核" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="mulipleCheckdialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitMulipleCheck">确 定</el-button>
        </div>
      </el-dialog>


    </div>
  </div>
</template>

<script>
import {getAllPostInfoByAdmin,updateCheckByPostId,updatePost,deletePost} from '@/api/Discussion'
import {deleteIdle, updateCheckByIdleId} from "@/api/Resale";


export default {
  name: "information_main",
  data() {
    return {
      //筛选
      fiter_check:'',
      //搜索相关功能
      findName:'',
      postContainerPage:0, // 分页的数据：当前页数
      postContainerSize:0, // 分页的数据：每页的数量
      total:0,
      postData: [],
      showData:[],
      copyData:[],
      search_info:[],
      //  添加弹窗相关
      addialogVisible:false,
      Addform:{
        post_id:'',
        post_title:'',
        post_content:'',
        post_category:'',
        post_label:'',
        post_check:'',

      },
      //  编辑功能相关
      editdialogVisible:false,
      Editform:{
        post_id:'',
        post_title:'',
        post_content:'',
        post_category:'',
        post_label:'',

      },
      category:[
        {
          id:'1',
          label:'求助问答',
          value:1
        },
        {
          id:'2',
          label:'学长学姐经验贴',
          value:2
        },
        {
          id:'3',
          label:'日常生活',
          value:3
        },
        {
          id:'4',
          label:'其他',
          value:4
        },

      ],
      formLabelWidth: '100px',
      //表单校验规则
      rules: {
        post_title: [
          { required: true, message: '请输入帖子标题', trigger: 'blur'},
          { min:3, max: 20, message: '长度在 3 到 50 个字符', trigger: 'blur'}
        ],
        post_label: [
          { message: '请输入帖子标签', trigger: 'blur'},
          { min:1, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
        ],
        post_category: [
          { required: true, message: '请选择帖子类别', trigger: 'change'}
        ],
        post_content: [
          { required: true, message: '请输入帖子内容', trigger: 'blur'},
          { min:1, max: 2000, message: '长度在 1 到 2000 个字符', trigger: 'blur'}
        ]

      },
      //审核弹窗相关
      checkdialogFormVisible:false,
      checkform:{
        check:'',

      },
      post_id_check:'',
      user_id_check:'',
      //  批量审核
      multipleSelection: [],
      mulipleIdle:{
        multipleCheck:'',
      },
      mulipleCheckdialogFormVisible:false,


    }
  },

  methods: {
    //获取全部帖子信息
    init(){
      getAllPostInfoByAdmin({}).then(res=>{
        this.postData=res.data.data;
        this.copyData=res.data.data;
        this.getShowPost();
      });
    },
    //审核
    check(index, row){
      this.checkdialogFormVisible=true; //打开弹窗
      this.post_id_check=row.post_id;
      this.user_id_check=row.user_id;
    },
    submitCheck(){
      if(this.checkform.check.length==0){
        this.$msg.warning("请选择！");
        return false;
      }
      this.checkSave(this.post_id_check,this.checkform.check);
    },
    //修改审核情况
    checkSave(post_id,post_id_check){
      updateCheckByPostId({
        post_id_check: post_id_check,
        post_id:post_id,user_id:this.user_id_check
      }).then(res=>{
        if(res.data.code===1)
        {
          this.$msg.success("修改成功！");
          //刷新表格数据
        }
        else
        {
          this.$msg.error("修改失败！");
        }
        this.checkdialogFormVisible=false;
        this.init();
      });

    },
    //编辑信息  打开编辑弹窗
    edit(index, row) {

      this.editdialogVisible=true;


      // console.log(index);
      // console.log(row);
      this.Editform.post_id=row.post_id;
      this.Editform.post_title=row.post_title;
      this.Editform.post_content=row.post_content;
      this.Editform.post_label=row.post_label;
      // this.form.user_id=row.user_id;
      // this.form.post_img=row.post_img;

      if(row.post_category==1){
        this.Editform.post_category="求助问答";

      }else if(row.post_category==2){
        this.Editform.post_category="学长学姐经验贴";

      }else if(row.post_category==3){
        this.Editform.post_category="日常生活";

      }else if(row.post_category==4){
        this.Editform.post_category="其他";
      }




    },
    //提交数据 修改
    editSave(formName)
    {

      if(this.Editform.post_category==="求助问答"){
        this.Editform.post_category=1;

      }else if(this.Editform.post_category==="学长学姐经验贴"){
        this.Editform.post_category=2;

      }else if(this.Editform.post_category==="日常生活"){
        this.Editform.post_category=3;

      }else if( this.Editform.post_category==="其他"){
        this.Editform.post_category=4;
      }

      //验证
      this.$refs[formName].validate((valid) => {
        if (valid) {

          //再次确认
          this.$confirm('确认修改?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.updateSave();

          }).catch(() => {
            this.$msg.error("取消修改！");
          });

        } else {
          this.$msg.error("修改失败！");
          return false;
        }
      });

    },
    //连接后端  进行修改
    updateSave(){

      updatePost({
        form:this.Editform,
        post_id:this.Editform.post_id
      }).then(res=>{
        if(res.data.code===1)
        {
          this.$msg.success("成功修改！");
          this.editdialogVisible=false;
          this.init();
        }
        else
        {
          this.$msg.error("修改失败！");
        }

        if(this.Editform.post_category==1){
          this.Editform.post_category="求助问答";

        }else if(this.Editform.post_category==2){
          this.Editform.post_category="学长学姐经验贴";

        }else if(this.Editform.post_category==3){
          this.Editform.post_category="日常生活";

        }else if(this.Editform.post_category==4){
          this.Editform.post_category="其他";
        }
      })

    },
    //删除
    handleDelete(index, row) {
      //再次确认
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteSave(row.post_id);
      }).catch(() => {
        this.$msg.error("取消删除！");
      });

    },
    //连接后端，进行删除
    deleteSave(post_id){

      deletePost({
        post_id:post_id,
      }).then(res=>{
        if(res.data.code==1){
          this.$msg.success("删除成功！");
        }else{
          this.$msg.error("删除失败！");
        }
        this.init();
      })

    },
    //打开添加的弹窗
    addOpen(){
      this.addialogVisible=true;
    },
    submitAdd(formName){

      //验证
      this.$refs[formName].validate((valid) => {
        if (valid) {

          //再次确认
          this.$confirm('确认发布?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            this.addSave();

          }).catch(() => {
            this.$msg.error("发布失败！");
          });

        } else {
          this.$msg.error("发布失败！");
          return false;
        }
      });

    },
    //连接后端 添加
    async addSave(){

      const {data: res} =await this.$ajax.post('/api/Pee/addPeeInfo',
          {AddForm: this.Addform, token: window.sessionStorage.getItem('token')})

      console.log(res);
      if(res.code===1)
      {
        this.$msg.success("发布成功！");
        //刷新表格数据
        this.init();
        //关闭弹窗
        this.addialogVisible=false;

      }
      else
      {
        this.$msg.error("发布失败！");
      }



    },
    //重置按钮
    clearInput(formName){
      this.$refs[formName].resetFields();
    },
    openCancelEdit(){
      this.editdialogVisible=false;
    },
    //  关闭弹窗
    cancel() {
      this.addialogVisible = false
      // 点击取消按钮的时候清除输入框中的内容 清除验证
      //  this.$nextTick获取了节点之后进行操作
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });

    },
    // 右上角 × 取消按钮
    closeDiv() {

      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });

    },
    //清空搜索框
    clearFindInput(){
      this.findName="";
      this.init();
    },
    handleClose(){
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });
    },
    //取消选择
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;

    },
    //  批量审核
    handleMultipleCheck(){
      if (this.multipleSelection == '') {
        this.$message.error('您未选中任何闲置帖子，请重新操作！！！');
        return;
      }

      this.mulipleCheckdialogFormVisible=true;
    },
    submitMulipleCheck(){

      let checkArr = this.multipleSelection;  // multipleSelection存储了勾选到的数据
      let post_ids = [];
      checkArr.forEach(function (item) {
        post_ids.push(item.post_id);
      });
      updateCheckByPostId({
        post_id_check: this.mulipleIdle.multipleCheck,
        post_id:post_ids,
      }).then(res=>{
        if(res.data.code===1)
        {
          this.$msg.success("批量审核成功！");
          //刷新表格数据
        }
        else
        {
          this.$msg.error("批量审核失败！");
        }
        this.mulipleCheckdialogFormVisible=false;
        this.init();
      })

    },
    //  批量删除
    handleMultipleDelete(){

      if (this.multipleSelection == '') {
        this.$message.error('您未选中任何闲置帖子，请重新操作！！！');
        return;
      }

      let checkArr = this.multipleSelection;  // multipleSelection存储了勾选到的数据
      let post_ids = [];
      checkArr.forEach(function (item) {
        post_ids.push(item.post_id);
      });

      //再次确认
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        deletePost({
          post_id:post_ids,
        }).then(res=>{
          if(res.data.code==1){
            this.$msg.success("批量删除成功！");
          }else{
            this.$msg.error("删除失败！");
          }
          this.init();
        });

      }).catch(() => {
        this.$msg.error("取消删除！");
      });


    },
    //分页
    getShowPost(){

      this.postContainerSize=parseInt(10);
      this.showData = this.postData.slice((this.postContainerPage - 1) * this.postContainerSize, this.postContainerPage * this.postContainerSize);
      this.total=parseInt(this.postData.length);

    },
    //根据闲置物品名进行搜索
    searchByTitle(){

      var search=this.findName;
      if(search==""||search==null)
      {
        this.$msg.error('输入框不能为空！');
        this.init();
      }
      else {
        //执行本地过滤
        var search_list=this.copyData;
        this.search_info=[];  //装搜索结果的容器

        for(let i=0;i<search_list.length;i++)
        {
          if(search_list[i].post_title.indexOf(search)>=0)
          {
            this.search_info.push(search_list[i]);
          }
        }
        if(this.search_info.length==0)
        {
          this.$msg.error('未找到相关结果,刷新一下~');
        }
        this.postData=this.search_info;
        //分页
        this.postContainerPage=parseInt(1);
        this.getShowPost();

        //清空搜索框
        // this.findName="";
      }

    },
    //  数据筛选
    changecheck(){

      var search=this.fiter_check;
      //执行本地过滤
      var search_list=this.copyData;
      this.search_info=[];  //装搜索结果的容器
      for(let i=0;i<search_list.length;i++)
      {
        if(search_list[i].post_check==search)
        {
          this.search_info.push(search_list[i]);
        }
      }
      if(this.search_info.length==0)
      {
        this.$msg.error('未找到相关结果,刷新一下~');
      }
      this.postData=this.search_info;
      //分页
      this.postContainerPage=parseInt(1);
      this.getShowPost();


    },
    //page改变时的回调函数，参数为当前页码
    handleCurrentChange(val) {

      console.log(`当前页: ${val}`);
      this.postContainerPage= parseInt(val);
      this.getShowPost();
    },
    // 筛选器
    filterHandler(value, row, column) {
      const property = column['property'];
      return row[property] === value;
    },
    filterChange (value) {
      console.log(value)
    },



  },
  created() {

    let _this=this;

    _this.postContainerPage=parseInt(1);

    _this.init();

    _this.$refs.table.doLayout();


  },
}
</script>

<style scoped>
.btnfontClass{
  font-size: 15px;
}
.el-pagination {
  text-align: center;
}
.typeClass{
  font-size: 14px;
}
/*表格展开功能样式*/
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 70%;
}
</style>
